//
//  YKFragmentHeaderView.swift
//  YKSwiftViews
//
//  Created by edward on 2023/10/25.
//  Copyright © 2023 Edward（本内容遵循MIT协议）. All rights reserved.
//

import UIKit

internal protocol YKFragmentHeaderViewDelegate: NSObjectProtocol {
    
    func sizeOfItem(_ indexPath:IndexPath) -> CGSize
    
    func numberOfItem() -> Int
    
    func setupSubView(_ indexPath:IndexPath, itemView:UIView, isSelect:Bool) -> UIView
    
    func didSelet(with indexPath:IndexPath)
    
    func headerViewScrollDidAnimated() -> Bool
    
    func viewDidDisappear(_ index:Int)
    
    func viewDidAppear(_ index:Int)
}



class YKFragmentHeaderView: UIView {
    
    private let yk_fragment_header_sub_cell_key = "yk_fragment_header_sub_cell_key"

    internal weak var delegate:YKFragmentHeaderViewDelegate? {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    override var frame: CGRect {
        didSet {
            for view in self.subviews {
                view.removeFromSuperview()
            }
            
            self.ui()
        }
    }
    
    private var currentIndex:Int = 0
    private var lastControllerPage:Int = 0
    
    private lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
        collectionView.bounces = false
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        
        collectionView.alwaysBounceVertical = false
        collectionView.alwaysBounceHorizontal = false
        
        collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: yk_fragment_header_sub_cell_key)
        
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.ui()
    }
    
    convenience init(frame:CGRect,delegate:YKFragmentHeaderViewDelegate) {
        self.init(frame: frame)
        
        self.delegate = delegate
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.collectionView.frame = self.bounds
        self.collectionView.reloadData()
    }
    
}

private extension YKFragmentHeaderView {
    
    func ui() {
        
        self.addSubview(self.collectionView)
    }
}


internal extension YKFragmentHeaderView {
    
    func reload() {
        
        self.collectionView.reloadData()
    }
    
    func scroll(_ index:Int) {
        
        self.currentIndex = index
        self.reload()
        
        
        DispatchQueue.main.async {
            
            let count = self.collectionView.numberOfItems(inSection: 0)
            
            if index < count {
                
                let isAniMated = self.delegate?.headerViewScrollDidAnimated() ?? true
                
                if index == 0 {
                    self.collectionView.scrollToItem(at: IndexPath.init(row: index, section: 0), at: .left, animated: isAniMated)
                }else if index == (count - 1) {
                    self.collectionView.scrollToItem(at: IndexPath.init(row: index, section: 0), at: .right, animated: isAniMated)
                }else if self.lastControllerPage < index {
                    if (index + 1) == (count - 1) {
                        self.collectionView.scrollToItem(at: IndexPath.init(row: (count - 1), section: 0), at: .right, animated: isAniMated)
                    }else {
                        self.collectionView.scrollToItem(at: IndexPath.init(item: (index + 1), section: 0), at: .right, animated: isAniMated)
                    }
                }else if self.lastControllerPage > index {
                    if (index - 1) == 0 {
                        self.collectionView.scrollToItem(at: IndexPath.init(row: 0, section: 0), at: .left, animated: false)
                    }else {
                        self.collectionView.scrollToItem(at: IndexPath.init(row: (index - 1), section: 0), at: .left, animated: isAniMated)
                    }
                }
                
                self.delegate?.viewDidDisappear(self.lastControllerPage)
                
                self.lastControllerPage = index
                
                self.delegate?.viewDidAppear(index)
            }
        }
        
    }
}

extension YKFragmentHeaderView: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let item = self.delegate?.numberOfItem() {
            return item
        }
        return 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: yk_fragment_header_sub_cell_key, for: indexPath)
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        if let view = self.delegate?.setupSubView(indexPath, itemView: cell.contentView, isSelect: indexPath.row == self.currentIndex) {
            cell.contentView.addSubview(view)
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let size = self.delegate?.sizeOfItem(indexPath) {
            return size
        } else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.delegate?.didSelet(with: indexPath)
    }
}
